package com.hangsu.train.components.configuration;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hangsu.train.components.entity.Task;
import com.hangsu.train.components.service.TaskService;
import com.hangsu.train.components.web.job.ReportJob;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Scheduler;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lyy
 */
@Slf4j
@Configuration
public class QuartzConfiguration {

    @Resource
    private TaskService taskService;

    @Resource
    private ObjectMapper objectMapper;

    @PostConstruct
    public void initJobs() throws JsonProcessingException {
        log.info("init jobs");
        List<Task> tasks = taskService.getAll();
        if (tasks != null && !tasks.isEmpty()) {
            for (Task t : tasks) {
                if (t.getState()!=null && t.getState() == 1) {
                    taskService.removeJob(String.valueOf(t.getId()));
                    Map<String, Object> params = new HashMap<>();
                    if (StringUtils.isNotEmpty(t.getParams())){
                        params = objectMapper.readValue(t.getParams(), Map.class);
                    }
                    taskService.addJob(String.valueOf(t.getId()), t.getCron(), params, ReportJob.class);
                }
            }
        }
    }
}